﻿using ReflectionStudio.Core.Events;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using WPFExcelReport.Helpers;
namespace WPFExcelReport
{
    public class AMServer
    {
        ApplicationBase app
        {
            get
            {
                return ApplicationBase.Instance;
            }
        }
        VICC_ZLAN _VZL;
        public VICC_ZLAN VZL
        {
            get
            {
                if (_VZL == null)
                {
                    _VZL = new VICC_ZLAN();
                }
                return _VZL;

            }
        }
        private DataTable _TBZL;
        public DataTable TBZL
        {
            get
            {
                if (_TBZL == null)
                {
                    VZL.dwData = VZL.TBMain.NewRow();
                    VZL.dwData["MANDANT"] = app.Mandant;
                    VZL.SResult = VZL.QICC_ZLAN05(VZL.dwData);
                    _TBZL = VZL.SResult.Tables[0].Copy();
                }
                return _TBZL;
            }
        }
        DataTable _TBZLAM;
        public DataTable TBZLAM
        {
            get
            {
                if (_TBZLAM == null)
                {
                    VZL.dwData = VZL.TBMain.NewRow();
                    VZL.dwData["MANDANT"] = app.Mandant;
                    VZL.SResult = VZL.QICC_ZLAN03(VZL.dwData);
                    _TBZLAM = VZL.SResult.Tables[0].Copy();
                }
                return _TBZLAM;
            }
        }
        public string DEVTYP
        {
            get;
            set;
        }
        private Socket serverSocket; 
        
        AMClient Client;
        Dictionary<string, AMClient> _Clients;
        public Dictionary<string, AMClient> Clients
        {
            get
            {
                if (_Clients == null)
                {
                    _Clients = new Dictionary<string, AMClient>();
                }
                return _Clients;
            }
        }
        public int ServicePort = 1;
        public AMServer(int pointInt)
        {
            ServicePort = pointInt;

        }
        public string PLCIP
        {
            get;
            set;
        }
        bool IsRun = false;
        bool _IsPortReaday = false;
        public bool IsPortReaday
        {
            get
            {
                return Client.IsPortReaday;
            }

        }
        public Queue<CommandQ> SendQ = new Queue<CommandQ>();


        public bool IsListening = false;
        public bool InitSocketServer()
        {
            IPAddress localIp = app.SockeSerIP;
            if (localIp == null)
            {
                localIp = IPAddress.Parse("127.0.0.1");
            }
            try
            {
                if (serverSocket == null)
                {
                    serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    serverSocket.Bind(new IPEndPoint(localIp, ServicePort));
                    serverSocket.Listen(10);
                    Thread myThread = new Thread(ListenClientConnect);
                    myThread.Start();
                    IsListening = true;
                }
            }
            catch (Exception ex)
            {
                IsListening = false;
                Helpers.LogHelper.error(ex.Message + ex.StackTrace);
            }
            return IsListening;
        }

        public void ZLResetListen()
        {
            _TBZL = null;
            _TBZLAM = null;
            foreach (KeyValuePair<string, AMClient> kp in Clients)
            {
                kp.Value.CloseConnection();
            }
            if (TBZL == null)
            {

            }
            if (TBZLAM == null)
            {
                app.IsOnline = true;
            }
            InitSocketServer();
        }
        public void ZLStopListen()
        {
            _TBZL = null;
            _TBZLAM = null;
            foreach (KeyValuePair<string, AMClient> kp in Clients)
            {
                kp.Value.CloseConnection();
            }
            if (TBZL == null)
            {

            }
            if (TBZLAM == null)
            {
                app.IsOnline = true;
            }
        }

        /// <summary>  
        /// 监听客户端连接  
        /// </summary>  
        private void ListenClientConnect()
        {
            while (true)
            {
                try
                {
                    Socket clientSocket = serverSocket.Accept();
                    Client = new AMClient(clientSocket);
                    if (TBZL == null)
                    {
                        if (TBZLAM == null)
                        {
                            app.IsOnline = true;
                        }
                    } 
                    Clients[Client.EndPoint] = Client;
                    Helpers.LogHelper.info("AMServer"+Client.EndPoint + "...Client joined......"); 
                    CleanDisconntect();
                }
                catch (Exception ex)
                {
                    LogHelper.error(ex.Message);
                }
            }
        } 
        private void CleanDisconntect()
        {
            
            List<string> keys = new List<string>();
            foreach (KeyValuePair<string, AMClient> kp in Clients)
            {
                if (!kp.Value.SocketClient.Connected)
                {
                    keys.Add(kp.Key);
                }
            }

            foreach (string key in keys)
            {
                Clients.Remove(key);
            }
        }
        
    }
}